﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ERP_RORZE_SYSTEM;

namespace ERP_RORZE_DLL.Business
{
    public partial class panel_ReportPOCover : UserControl
    {
        private INISettings mySetting;
        private SqlConnection myConnection;

        public panel_ReportPOCover()
        {
            InitializeComponent();            

            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            LoadPOID();
            this.reportType.SelectedIndex = 0;

            this.buttonExport.Visible = false;
        }
        
        private void LoadPOID()
        {
            this.poID.Properties.Items.Clear();
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT ID FROM [241_PO] WHERE Cancelled=0 AND Change=0 ORDER BY ID";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["ID"].ToString();
                    item.Value = dataReader["ID"].ToString();
                    this.poID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get POID list");
            }
        } 

        private void buttonView_Click(object sender, EventArgs e)
        {
            this.buttonExport.Visible = false;

            if (this.poID.SelectedIndex < 0)
            {
                MessageBox.Show("Please select POID to view report");
            }
            else
            { 
                ComboboxItem item = (ComboboxItem)poID.SelectedItem;

                switch (this.reportType.SelectedIndex)
                {
                    case 0:
                        reportDocument.DocumentSource = null;
                        rpt_POCover POCover = new rpt_POCover();
                        POCover.po_id = item.Value.ToString();                        
                        POCover.LoadData();
                        POCover.CreateDocument();
                        reportDocument.DocumentSource = POCover;                        
                        break;
                    case 1:
                        this.buttonExport.Visible = true;
                        reportDocument.DocumentSource = null;
                        rpt_PODetails PODetails = new rpt_PODetails();
                        PODetails.po_id = item.Value.ToString();
                        PODetails.LoadData();
                        PODetails.CreateDocument();
                        reportDocument.DocumentSource = PODetails;
                        break;
                } 
            }  
        }

        private void poID_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.buttonExport.Visible = false;
        }

        private void buttonExport_Click(object sender, EventArgs e)
        {
            if (this.poID.SelectedIndex < 0)
            {
                MessageBox.Show("Please select POID to view report");
            }
            else
            {
                ComboboxItem item = (ComboboxItem)poID.SelectedItem;

                DataSet sourceDataSet = new DataSet();
                SQLManagement mySQLManagement = new SQLManagement();
                mySQLManagement.SQLConnectionString = mySetting.SQLConnectionString;
                string sql = "SELECT TOP 100 PERCENT t1.[POID], t2.PartNo AS RRCPartNo, t1.[OrderNo], t2.[IQID],"
                    + " t2.[PartEnglishName] AS PartName, t7.[EnglishName], ISNULL(t2.PartNoPurchase, t2.PartNo) AS PartNo,"
                    + " t3.[MakerName] AS Maker, t2.[ROHS], t1.[Quantity], t2.[BuyingUnit] AS UnitID, ROUND(t1.[UnitPrice], 2) AS Price,"
                    + " ROUND((t1.[Quantity] * t1.[UnitPrice]), 2) AS Amount, t1.[CurrencyID],"
                    + " CONVERT(VARCHAR(10), t1.[DeliveryDate], 111) AS DeliveryDate,"
                    + " t6.[TransportName] AS Way, t5.[DeliveryTermName], t2.[PackingNote], t2.[Remark] AS [Note]"
                    + " FROM [241_PODetails] AS t1 LEFT JOIN"
                    + " [222_Part] AS t2 ON t1.[PartNo] COLLATE Japanese_Unicode_CI_AI =t2.[PartNo] LEFT JOIN"
                    + " [222_Maker] AS t3 ON t2.[MakerID]=t3.[MakerID] LEFT JOIN"
                    + " [222_DeliveryTerm] AS t5 ON t1.[DeliveryTermID]=t5.[DeliveryTermID] LEFT JOIN"
                    + " [222_Transport] AS t6 ON t1.[TransportID]=t6.[TransportID] LEFT JOIN"
                    + " [222_IQ] AS t7 ON t2.[IQID]=t7.[IQID]"
                    + " WHERE t1.POID='" + item.Value.ToString() + "' AND t1.Cancelled=0 AND t1.Change=0";
                sourceDataSet = mySQLManagement.SQL_Query(sql);
                if (sourceDataSet != null)
                {
                    foreach (DataRow result_row in sourceDataSet.Tables[0].Rows)
                    {
                        if (result_row["UnitID"].ToString().Trim().Length > 0)
                        {
                            if (((int)(result_row["UnitID"].ToString().Trim()[0])) == 65402)
                            {
                                result_row.BeginEdit();
                                result_row["UnitID"] = "PC";
                                result_row.EndEdit();
                            }
                        }
                    }
                    gridPOExport.DataSource = sourceDataSet.Tables[0];                    
                }
                else
                {
                    MessageBox.Show("There is no data to export.");
                    DataTable newTable = new DataTable();
                    newTable.Columns.Add("POID", typeof(string));
                    newTable.Columns.Add("RRCPartNo", typeof(string));
                    newTable.Columns.Add("OrderNo", typeof(string));
                    newTable.Columns.Add("IQID", typeof(string));
                    newTable.Columns.Add("PartName", typeof(string));
                    newTable.Columns.Add("IQName", typeof(string));
                    newTable.Columns.Add("PartNo", typeof(string));
                    newTable.Columns.Add("Maker", typeof(string));
                    newTable.Columns.Add("RoHS", typeof(bool));
                    newTable.Columns.Add("Quantity", typeof(float));
                    newTable.Columns.Add("UnitID", typeof(string));
                    newTable.Columns.Add("Price", typeof(float));
                    newTable.Columns.Add("Amount", typeof(float));
                    newTable.Columns.Add("CurrencyID", typeof(string));
                    newTable.Columns.Add("DeliveryDate", typeof(string));
                    newTable.Columns.Add("Way", typeof(string));
                    newTable.Columns.Add("DeliveryTermName", typeof(string));
                    newTable.Columns.Add("PackingNote", typeof(string));
                    newTable.Columns.Add("Note", typeof(string));
                    gridPOExport.DataSource = newTable;
                }
                
                POExport.Columns[0].Caption = "PO ID";
                POExport.Columns[1].Caption = "RRC Part No.";
                POExport.Columns[2].Caption = "Order No.";
                POExport.Columns[3].Caption = "IQ No.";
                POExport.Columns[4].Caption = "Part Name Densan";
                POExport.Columns[5].Caption = "Part Name IQ";
                POExport.Columns[6].Caption = "Part No.";
                POExport.Columns[7].Caption = "Maker Name";
                POExport.Columns[8].Caption = "RoHS";
                POExport.Columns[9].Caption = "Q'ty";
                POExport.Columns[10].Caption = "Unit";
                POExport.Columns[11].Caption = "Unit Price";
                POExport.Columns[12].Caption = "Amount";
                POExport.Columns[13].Caption = "Currency";
                POExport.Columns[14].Caption = "Delivery Date";
                POExport.Columns[15].Caption = "Way";                
                POExport.Columns[16].Caption = "Delivery Term";
                POExport.Columns[17].Caption = "Packing Note";
                POExport.Columns[18].Caption = "Note";                

                Cursor currentCursor = Cursor.Current;
                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    SaveFileDialog saveFDlg = new SaveFileDialog();
                    saveFDlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    saveFDlg.Filter = "Microsoft Office Excel|*.xlsx";
                    saveFDlg.Title = "Save As";                    
                    saveFDlg.FileName = "PODocument.xlsx";
                    if (saveFDlg.ShowDialog(this) == DialogResult.OK)
                    {
                        if (!string.IsNullOrEmpty(saveFDlg.FileName))
                        {
                            POExport.OptionsPrint.PrintDetails = true;
                            POExport.OptionsPrint.ExpandAllDetails = true;
                            POExport.OptionsPrint.AutoWidth = false;
                            POExport.OptionsPrint.UsePrintStyles = true;
                            DevExpress.XtraPrinting.XlsxExportOptions myOptions = new DevExpress.XtraPrinting.XlsxExportOptions();
                            //myOptions.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Text;
                            myOptions.ShowGridLines = true;
                            myOptions.SheetName = "FIm_PODetailData";
                            POExport.BestFitColumns();
                            POExport.ExportToXlsx(saveFDlg.FileName, myOptions);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Warning!");
                }
                finally
                {
                    Cursor.Current = currentCursor;
                }
            }
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadPOID();
        }
    }
}
